package com.gavindon.android

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.ViewModelProviders
import com.bumptech.glide.Glide
import com.gavindon.android.base.BaseActivity
import com.gavindon.android.base.SP_TOKEN
import com.gavindon.android.entity.LoginStatus
import com.gavindon.android.network.BASE_URL_IMG
import com.gavindon.android.network.DataResult
import com.gavindon.android.utils.*
import com.gavindon.android.view.education.SmartEducationActivity
import com.gavindon.android.view.order.OrderActivity
import com.gavindon.android.view.record.RecordActivity
import com.gavindon.android.view.search.SearchActivity
import com.gavindon.android.view.start.LoginActivity
import com.gavindon.android.viewmodel.CommonViewModel
import com.gavindon.android.viewmodel.HomeViewModel
import com.gavindon.android.widget.banner.BannerView
import com.orhanobut.logger.Logger
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.model.VideoOptionModel
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import kotlin.system.exitProcess


class HomeActivity : BaseActivity() {

    private val fmlRecommend: FrameLayout by lazy {
        findViewById(R.id.fml_recommend)
    }
    private val fmlNew: FrameLayout by lazy {
        findViewById(R.id.fml_new)
    }
    private val ivRecommend: ImageView by lazy {
        findViewById(R.id.iv_recommend)
    }
    private val tvUserInfo: TextView by lazy {
        findViewById(R.id.tvUserInfo)
    }
    private val ivUserInfo: ImageView by lazy {
        findViewById(R.id.iv_userInfo)
    }

    private val ivNew: ImageView by lazy {
        findViewById(R.id.iv_new)
    }
    private val ivExit: ImageView by lazy {
        findViewById(R.id.iv_exit)
    }

    private val fmlMyStudy: FrameLayout by lazy {
        findViewById(R.id.fml_my_study)
    }
    private val fmlCollect: FrameLayout by lazy {
        findViewById(R.id.fml_collect)
    }
    private val fmlSmartEducation: FrameLayout by lazy {
        findViewById(R.id.smart_education)
    }
    private val fmlSmartMedical: FrameLayout by lazy {
        findViewById(R.id.smart_medical)
    }

    /*乡村振兴*/
    private val fmlSeniorUniversity: FrameLayout by lazy {
        findViewById(R.id.senior_university)
    }

    /*老年大学*/
    private val fmlRural: FrameLayout by lazy {
        findViewById(R.id.rural_revitalization)
    }

    /*学习型家庭*/
    private val fmlLearningFamily: FrameLayout by lazy {
        findViewById(R.id.learning_family)
    }

    /*学习型家庭*/
    private val fmlVip: FrameLayout by lazy {
        findViewById(R.id.fml_vip)
    }

    private val csSearch: ConstraintLayout by lazy {
        findViewById(R.id.cs_search)
    }
    private val csMain: ConstraintLayout by lazy {
        findViewById(R.id.csl)
    }

    override val layoutId = R.layout.activity_home

    private lateinit var homeViewModel: HomeViewModel
    private lateinit var commonViewModel: CommonViewModel
    override fun onInit(savedInstanceState: Bundle?) {
        homeViewModel = getViewModel()
        commonViewModel = getViewModel()
        //全局设置播放器内核 exo不会音画不同步会黑屏。
        PlayerFactory.setPlayManager(Exo2PlayerManager::class.java)
        val list: MutableList<VideoOptionModel> = mutableListOf()
        val videoOptionMode04 =
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0) //是否开启缓冲
        val videoOptionModel2 =
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1)
        val videoOptionModel5 =
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1)
        list.add(videoOptionModel2)
        list.add(videoOptionMode04)
        GSYVideoManager.instance().optionModelList = list
        fmlRecommend.requestFocus()

        hotRecommend()
        banner3()
        news()
//        clickForResult(csSearch) {
//            startActivity<SearchActivity>()
//        }
        csSearch.clickFree {
            startActivity<SearchActivity>()
        }
        /* clickForResult(fmlSmartEducation) {
             startActivity<SmartEducationActivity>(
                 Pair("courseType", CourseType.EDUCATION.ordinal),
                 Pair("typeName", CourseType.EDUCATION.getName())
             )
         }*/

        fmlSmartEducation.setOnClickListener {
            startActivity<SmartEducationActivity>(
                Pair("courseType", CourseType.EDUCATION.ordinal),
                Pair("typeName", CourseType.EDUCATION.getName())
            )
        }

        /*    clickForResult(fmlSmartMedical) {
                startActivity<SmartEducationActivity>(
                    Pair("courseType", CourseType.CREATE.ordinal),
                    Pair("typeName", CourseType.CREATE.getName())
                )
            }*/
        fmlSmartMedical.setOnClickListener {
            startActivity<SmartEducationActivity>(
                Pair("courseType", CourseType.CREATE.ordinal),
                Pair("typeName", CourseType.CREATE.getName())
            )
        }
        /*  clickForResult(fmlRural) {
              startActivity<SmartEducationActivity>(
                  Pair("courseType", CourseType.OLD.ordinal),
                  Pair("typeName", CourseType.OLD.getName())
              )
          }*/
        fmlRural.setOnClickListener {
            startActivity<SmartEducationActivity>(
                Pair("courseType", CourseType.OLD.ordinal),
                Pair("typeName", CourseType.OLD.getName())
            )
        }
        /*  clickForResult(fmlSeniorUniversity) {
              startActivity<SmartEducationActivity>(
                  Pair("courseType", CourseType.COUNTRY.ordinal),
                  Pair("typeName", CourseType.COUNTRY.getName())
              )
          }*/
        fmlSeniorUniversity.setOnClickListener {
            startActivity<SmartEducationActivity>(
                Pair("courseType", CourseType.COUNTRY.ordinal),
                Pair("typeName", CourseType.COUNTRY.getName())
            )
        }
        /*   clickForResult(fmlLearningFamily) {
               startActivity<SmartEducationActivity>(
                   Pair("courseType", CourseType.STUDY.ordinal),
                   Pair("typeName", CourseType.STUDY.getName())
               )
           }*/
        fmlLearningFamily.setOnClickListener {
            startActivity<SmartEducationActivity>(
                Pair("courseType", CourseType.STUDY.ordinal),
                Pair("typeName", CourseType.STUDY.getName())
            )
        }
        ivExit.setOnClickListener {
            if (LoginStatus.userInfoResp != null) {
                SpUtils.clearName(SP_TOKEN)
                LoginStatus.userInfoResp = null
                LoginStatus.hasLogin = false
                LoginStatus.token = ""
                getUserInfo()
                toast("您已退出登录")
            } else {
                toast("您还未登录")
            }
        }
        //index和个人中心左侧列表索引对应
        clickForResult(fmlCollect) {
            startActivity<RecordActivity>(Pair("index", 0))
        }
        clickForResult(fmlMyStudy) {
            startActivity<RecordActivity>(Pair("index", 1))
        }
        fmlVip.click {
//            mToast()
            startActivity<OrderActivity>()
        }

        ivUserInfo.setOnClickListener {
            startActivity<LoginActivity>()

        }
    }

    /*热门推荐课程*/
    private fun hotRecommend() {
        homeViewModel.getRecommendLst().observe(this, {
            if (it is DataResult.Success) {
                val fileUrl = it.data[0].file.fileUrl
                Glide.with(this).load("$BASE_URL_IMG/$fileUrl").error(R.mipmap.img3)
                    .into(ivRecommend)
                /*      clickForResult(fmlRecommend) {
                          this.toFullVideoOrDetailPage(
                              it.data[0].subjectType,
                              it.data[0].courseId,
                              it.data[0].courseName
                          )
                      }*/

                fmlRecommend.clickFree {
                    this.toFullVideoOrDetailPage(
                        it.data[0].subjectType,
                        it.data[0].courseId,
                        it.data[0].courseName
                    )
                }

            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == requestLoginCode) {
            getUserInfo()
        }
    }

    override fun onStart() {
        super.onStart()
        getUserInfo()
    }

    private fun checkPayResult(id: String, orderType: String) {
        commonViewModel.checkIsCanLook(orderType, id).observe(this) {
            if (it is DataResult.Success) {
                if (!it.data.isNullOrEmpty()) {
                    when (it.data[0].validity) {
                        0 -> canLookListener?.invoke(false)
                        1 -> {
//                            toast("购买已过期")
                            canLookListener?.invoke(false)
                        }
                        2 -> {
                            toast("您已购买，可返回观看")
                            canLookListener?.invoke(true)
                        }
                    }
                } else {
                    canLookListener?.invoke(false)
                }

            } else {
                canLookListener?.invoke(false)
            }
        }
    }

    private var canLookListener: ((Boolean) -> Unit)? = null
    fun setCheckListener(listener: (Boolean) -> Unit) {
        this.canLookListener = listener
    }

    override fun onResume() {
        super.onResume()
        if (LoginStatus.userInfoResp != null) {
            tvUserInfo.text = LoginStatus.userInfoResp?.realName
            tvUserInfo.visibility = View.VISIBLE
            ivUserInfo.visibility = View.GONE
        } else {
            tvUserInfo.visibility = View.GONE
            ivUserInfo.visibility = View.VISIBLE
        }
    }

    private fun getUserInfo() {
        val token = SpUtils.get(SP_TOKEN, "")
        LoginStatus.token = token

//        if (LoginStatus.userInfoResp != null) {
//            tvUserInfo.text = LoginStatus.userInfoResp?.realName
//            tvUserInfo.visibility = View.VISIBLE
//            ivUserInfo.visibility = View.GONE
//            Logger.i(LoginStatus.token)
//        } else {
//            tvUserInfo.visibility = View.GONE
//            ivUserInfo.visibility = View.VISIBLE
//        }
        homeViewModel.getUserInfo().observe(this) {
            if (it is DataResult.Success) {
                LoginStatus.hasLogin = true
                LoginStatus.userInfoResp = it.data
                tvUserInfo.text = it.data.realName
                tvUserInfo.visibility = View.VISIBLE
                ivUserInfo.visibility = View.GONE
            } else {
                LoginStatus.hasLogin = false
                tvUserInfo.visibility = View.GONE
                ivUserInfo.visibility = View.VISIBLE
            }
        }
    }

    /*最新课程*/
    private fun news() {
        homeViewModel.getNewsLst().observe(this, {
            if (it is DataResult.Success) {
                val fileUrl = it.data[0].file.fileUrl
                Glide.with(this).load("$BASE_URL_IMG/$fileUrl").into(ivNew)
                /*   clickForResult(fmlNew) {
                       this.toFullVideoOrDetailPage(
                           it.data[0].subjectType,
                           it.data[0].courseId,
                           it.data[0].courseName
                       )
                   }*/
                fmlNew.clickFree {
                    this.toFullVideoOrDetailPage(
                        it.data[0].subjectType,
                        it.data[0].courseId,
                        it.data[0].courseName
                    )
                }
            }
        })
    }

    private fun banner3() {
        val bannerView: BannerView = findViewById(R.id.banner3)
        val imgUrls = mutableListOf<String>()
        homeViewModel.getSliderBanner().observe(this, {
            if (it is DataResult.Success) {
                for (item in it.data) {
                    imgUrls.add("$BASE_URL_IMG/${item.file.fileUrl}")
                }
                bannerView.addViews(imgUrls.toList())
                bannerView.startFlipper()
                bannerView.addOnItemClickListener { pos ->
                    val itemData = it.data[pos]
                    /*          if (LoginStatus.hasLogin) {
                                  this.toFullVideoOrDetailPage(
                                      itemData.subjectType,
                                      itemData.courseId,
                                      itemData.courseName
                                  )
                              } else {
                                  toast("请先登录")
                                  this.startActivityForResult<LoginActivity>(requestLoginCode)
                              }*/

                    this.toFullVideoOrDetailPage(
                        itemData.subjectType,
                        itemData.courseId,
                        itemData.courseName
                    )

                }
            }

        })
    }

    private var lastExitTime = 0L
    override fun onBackPressed() {
        //大于2000ms则认为是误操作，使用Toast进行提示
        if (System.currentTimeMillis() - lastExitTime > 2000) {
            toast("再按一次退出程序")
            lastExitTime = System.currentTimeMillis()
        } else {
            this.finish()
            exitProcess(0)
        }
    }


}